/** 
 * 手动分页符 <div style="page-break-after:always"></div>
 * table前加 \`\`\`table class: "triLine allCenter noHead noDiff", title: "Title", css: ""
*/
var debugMd = !1;
if (!window.AIacnt) {
  var AIacnt = [
    // 向此数组中添加账户，当免登录字数用完后，将逐个使用本数组下的账户
    // {email:'',password:''},
  ];
}
var curAcnt = -1;
if (!window.AItoken) {
  // token优先使用
  var AItoken = new Set();
}
var curToken = -1;
var itToken = AItoken.values();
var Context = 0; // ChatGPT 上下文数量
var CTXT = [];
var tbfigN = 0;
const Prot = "\x68\x74\x74\x70\x3A\x2F\x2F";
// 思来想去，与其自己做解析，还不如首行写上类型，然后提供一个按钮供用户选择是否粘贴该类型的模板
const Template = {
  bar: `option = {
title:{
    text: '这里是标题',
},
xAxis: {
  type: 'category',
  data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  name: 'xAxis',
},
yAxis: {
  type: 'value',
  name: 'yAxis',
},
series: [{
    data: [120, 200, 150, 80, 70, 110, 130],
    type: 'bar'
  },{
    data: [50,130,120,160,80,150,90],
    type: 'bar'
  }
]
};`,
  line: ``,
  scatter: ``,
  pie: ``,
  polar: ``,
  bar_race: `
`,
};
const ExampleCode = `---
title: Title
author: author
creator: creator
subject: subject
keywords: [keyword1, keyword2]
header:  \${title}
footer: \${pageNo} / \${pageCount}
---

\`\`\`style
@media print {
  @page {
    size: A4 portrait !important;
    margin: 17mm 15mm;
  }
}
body #write{
  font-family: Consolas, Microsoft Yahei, Roman, "Cambria Math" , SimSun, monospace;
  width:100% !important;
  padding: 0 10px 500px 30px;
  counter-reset: h1 h2 h3 Figures Tables;
  --figPre: "图";
  --figSuf: " ";
  --tabPre: "表";
  --tabSuf: " ";
}
#write h1 {
  text-align:center;
  page-break-before:always;
}
code {
  font-family: Consolas;
  padding: 1px 2px;
}
#write p.title:before {
  font-family: Consolas, Microsoft Yahei;
  counter-increment: Figures;
  content: var(--figPre, "Fig") counter(h1) "-" counter(Figures) var(--figSuf," ") attr(alt);
  display: block;
  text-align: center;
}
#write figure p.title:before{
  counter-increment: Tables;
  content: var(--tabPre, "Tab") counter(h1) "-" counter(Tables) var(--tabSuf," ") attr(alt);
  text-align: left;
}
.md-toc-item.md-toc-h1, #write h1 {
  counter-increment: h1;
  counter-set: h2 0 Figures 0 Tables 0;
}
.md-toc-item.md-toc-h2, #write h2 {
  counter-increment: h2;
  counter-set: h3 0;
}
.md-toc-item.md-toc-h3, #write h3 {
  counter-increment: h3;
}
.md-toc-item.md-toc-h1 a:before, #write h1:before {
  content: counter(h1);
}
.md-toc-item.md-toc-h2 a:before, #write h2:before {
  content: counter(h1) "." counter(h2);
}
.md-toc-item.md-toc-h3 a:before, #write h3:before {
  content: counter(h1) "." counter(h2) "." counter(h3);
}
h1:before, h2:before, h3:before{
  color: #5A5A5A;
  margin-right:10px;
}
.md-toc-item a:before { margin-right:8px; }
.md-toc>*:last-child { counter-reset:h1 h2 h3;}
#write img {mix-blend-mode: multiply;}
\`\`\``;
function $q(s) {
  return document.querySelector(s);
}
const metaProperty = ["title", "xlabel", "ylabel", "xrange", "yrange"];
const chartType = ["bar", "scatter", "function"];
var ma = ($q("#typora-source .CodeMirror") || {}).CodeMirror;
var Coords = [0, 0];
// 导出为pdf时出现任何问题的调试方法：导出为html调试、观察DOM的变化
if (!window.MDexport) {
  var MDexport = false;
}

var write = $q("div#write");
var styleCustom = nE("style", "custom", 0);
document.head.appendChild(styleCustom);
var customScript = nE("script", "customScript", 0);
document.head.appendChild(customScript);
var mdfocus; // 当前焦点
var Blur = false;
var Paste = ($q("#context-menu-for-source") || {}).lastElementChild || undefined;
/**
 * <p>项目名称: ${project_name} </p> 
 * <p>文件名称: ${file_name} </p> 
 * <p>描述: [类型描述] </p>
 * <p>创建时间: ${date} </p>
 * <p>公司信息: ************公司 *********部</p> 
 * @param string e tagname
 * @param string id
 * @param string cla
 * @param string html
 * @author <a href="mail to: *******@******.com" rel="nofollow">作者</a>
 * @version v1.0
 * @returns Element
 * @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
 */
function nE(e, id = undefined, cla = undefined, html = "") {
  var ele = document.createElement(e);
  id && (ele.id = id);
  cla && (ele.className = cla);
  html && (ele.innerHTML = html);
  return ele;
}

function show(e) {
  e.style.display = "block";
}
function hide(e) {
  e.style.display = "none";
}
function getTip(str) {
  str = str.split("\n");
  var opt = { title: {}, xAxis: {}, yAxis: {} };
  str.forEach((v) => {
    var t = v.split(":");
    switch (t[0]) {
      case "title":
        opt.title = {};
        opt.title.text = t[1];
        break;
    }
    if (metaProperty.indexOf(t[0]) >= 0) {
      if (t[0].indexOf("range") >= 0) {
        eval("t[1] = " + t[1]);
      }
      opt[t[0]] = t[1];
    }
  });
  return opt;
}

function parseCode(pre, nofocus = false) {
  var lines = pre.querySelector(".CodeMirror-code");
  if (!lines || !echarts) {
    return;
  }
  pre.className = "md-fences md-end-block md-diagram md-fences-advanced ty-contain-cm modeLoaded" + (nofocus ? "" : " md-focus");
  var script = "";
  var metaLine = ""; // = lines.children[0].innerText;
  // 没有焦点获取到的innerText居然没有换行符
  lines.childNodes.forEach((v) => {
    script += v.textContent + "\n";
  });
  script = script.slice(0, -1);
  var ind = script.indexOf("\n");
  if (ind >= 0) {
    metaLine = script.substring(0, ind);
    script = script.substring(ind + 1);
  } else {
    debugMd && console.log("Echarts script:", script);
    return;
  }
  var classDiagram = "option",
    size = ["100%", "500px"],
    mode = "svg",
    theme = null;
  metaLine.split(" ").forEach((v) => {
    switch (true) {
      case /[ \t]+/.test(v):
        break;
      case /^\d+x\d+$/.test(v):
        size = v.split("x");
        v[0] += "px";
        v[1] += "px";
        break;
      case /^\d+$/.test(v):
        size = ["100%", v + "px"];
        break;
      case /^svg|canvas$/.test(v):
        mode = v;
        break;
      case /^dark$/.test(v):
        theme = v;
        break;
      default:
        break;
    }
  });
  if (size[0] == "100%") {
    size[0] = pre.clientWidth + "px";
  }
  var diag = pre.querySelector(".md-diagram-panel");
  if (!diag) {
    var diag = nE("div", 0, "md-diagram-panel md-fences-adv-panel", '<div class="md-diagram-panel-header"></div><div class="md-diagram-panel-preview"></div><div class="md-diagram-panel-error"></div>');
    pre.append(diag);
  }
  var chart = diag.querySelector(".md-diagram-panel-preview");
  var error = diag.querySelector(".md-diagram-panel-error");
  chart.style.cssText = `height:${size[1]};width:${size[0]};`;
  var myChart = echarts.init(chart, theme, { renderer: mode, height: size[1] });
  var option;
  try {
    eval(script);
    if (!option) {
      eval(metaLine + "\n" + script);
    }
    if (option) {
      if (MDexport) {
        option.animation = false;
      }
      if (classDiagram === "option") {
        // 添加对图例模板的解析代码
        debugMd && console.log(option);
      }
      myChart.setOption(option);
      if (MDexport) {
        hide(pre.firstChild);
        pre.style.marginBottom = "0";
      }
      error.innerHTML = "";
    } else {
      error.innerHTML = "ERROR(ECharts@5.4.1, mdEcharts@1.0.1)";
      chart.innerHTML = "";
    }
  } catch (err) {
    error.innerHTML = "ERROR: " + err + " (ECharts@5.4.1, mdEcharts@1.0.1)";
  }
  if (!nofocus) {
    var h = 30;
    var d = pre.querySelector(".md-diagram-panel.md-fences-adv-panel");
    d && (h = d.clientHeight + 30);
    pre.style.marginBottom = h + "px";
  }
}

// 粘贴示例代码，textarea可以多行，input不行
const Cinput = document.createElement("textarea");
function copyStr(str, pa = 0) {
  // 不能设置display none，只能脱离文档流、全透明
  Cinput.style.cssText = "opacity:0;position:absolute;z-index:-1;";
  document.body.appendChild(Cinput);
  Cinput.value = str;
  Cinput.select();
  document.execCommand("Copy");
  if (pa) {
    Paste.click();
  }
}
function debugAddInfo(str){
  let pre = nE('pre');
  pre.textContent = str;
  write.append(pre);
}
function addStyle(css) {
  let c = nE("style");
  c.innerHTML = css;
  document.head.append(c);
}
function imgProcess(v) {
  let n = v.nextElementSibling,
    t = v.getAttribute("alt");
  if (n && n.className !== "title") {
    n = false;
  }
  if (!t) {
    // svg下的title标签
    t = v.querySelector("title");
    if (t) {
      t = t.innerText;
    }
  }
  if (n) {
    if (n.getAttribute("alt") !== t) {
      n.setAttribute("alt", t);
    }
  } else if (t) {
    let p = v.parentElement;
    if(p.parentElement.children.length<2){
      v.classList.add("img-center");
      // if (MDexport)  debugAddInfo(v.parentElement.outerHTML+'    zoon: '+z)
    }
    let title = nE('p',0,'title');
    title.setAttribute('alt',t);
    p.append(title);
  }
}
function imgFloatProc(v,right=0){
  let p = v.parentElement;
  void v.offsetHeight; // 触发重排
  let h = 0;
  let w = 0;
  if(v.tagName==='IMG'){
    let zoom = v.style.zoom;
    if(zoom.endsWith('%')){
      zoom = parseFloat(zoom)/100;
    }else{
      zoom = parseFloat(zoom);
    }
    h = v.naturalHeight*zoom;
    w = v.naturalWidth*zoom;
  }else{
    h = v.clientHeight;
    w= v.clientWidth;
  }
  w=w+5+'px';
  // let dbstr = v.src+': \n'+p.outerHTML+'\n'+'\n'+h+' '+w+' 【1.1】 '+`clientH=${v.clientHeight} offsetH=${v.offsetHeight} zoom=${v.style.zoom}`;
  // if(MDexport)debugAddInfo(dbstr);
  if(right){
    p.style.paddingRight = w;
    p.minHeightRight = h;
  }else{
    p.style.paddingLeft = w;
    p.minHeightLeft = h;
  }
  let ph = Math.max(p.minHeightRight||0, p.minHeightLeft||0);
  p.style.minHeight = ph+'px';
}
function imgFloat(){
  if(MDexport){
    write.querySelectorAll("p:has(span)>small:first-child").forEach(v=>{imgFloatProc(v)});
    write.querySelectorAll("p:has(span)>small:last-child").forEach(v=>{imgFloatProc(v,1)});
  }
  else{
    write.querySelectorAll("p:has(span.md-plain)>.md-image:first-child").forEach(v=>{imgFloatProc(v)});
    write.querySelectorAll("p:has(span.md-plain)>.md-image:last-child").forEach(v=>{imgFloatProc(v,1)});
  }
  // 在实时编辑的时候，通过css p:has(span.md-plain:first-child)强制padding-left为0即可
}
function myTools() {
  if(Blur) return;
  if (MDexport) {
    write.querySelectorAll("p>img:only-child, svg[alt], p>.md-image:first-child>img, p>small:first-child>img, p>small:last-child>img").forEach(imgProcess);
    var ch = write.querySelector("pre.md-fences.md-end-block[lang=script]");
    if (ch) {
      hide(ch);
    }
  } else {
    write.querySelectorAll("p .md-image.md-img-loaded:only-child img, svg[alt], p>.md-image:first-child>img, p>.md-image:last-child>img").forEach(imgProcess);
  }
  imgFloat();
  let b = write.lastElementChild;
  // 当第一行的内容超过两个字时移除复制按钮
  if (b && b.tagName.toLowerCase() === "button" && write.firstElementChild.innerText.length > 2) {
    b.remove();
  }
  if (styleCustom.innerHTML.length < 5) {
    parseStyle();
  }
}

function parseHTML(pre, nofocus = false) {
  var lines = pre.querySelector(".CodeMirror-code");
  if (!lines) {
    return;
  }
  pre.className = "md-fences md-end-block md-diagram md-fences-advanced ty-contain-cm modeLoaded" + (nofocus ? "" : " md-focus");
  var script = lines.innerText.replaceAll("\u200B", "\n"); // innerText; &ZeroWidthSpace;
  var diag = pre.querySelector(".md-diagram-panel");
  if (!diag) {
    var diag = nE("div", 0, "md-diagram-panel md-fences-adv-panel", '<div class="md-diagram-panel-header"></div><div class="md-diagram-panel-preview"></div><div class="md-diagram-panel-error"></div>');
    pre.append(diag);
  }
  var chart = diag.querySelector(".md-diagram-panel-preview");
  chart.innerHTML = script;
  if (!nofocus) {
    var h = 30;
    var d = pre.querySelector(".md-diagram-panel.md-fences-adv-panel");
    d && (h = d.clientHeight + 30);
    pre.style.marginBottom = h + "px";
  }
  if (MDexport) {
    hide(pre.firstChild);
    pre.style.marginBottom = "0";
  }
}
function parseTable(pre) {
  var lines = pre.querySelector(".CodeMirror-code");
  var tbfig = pre.nextElementSibling;
  if (!lines || tbfig.tagName.toLowerCase() !== "figure") {
    return;
  }
  var opt = { location: "top" };
  var script = "opt={\n";
  if(lines){
  lines.childNodes.forEach((v) => {
    script += v.textContent;
  });}else{
    script += pre.textContent;
  }
  script += "\n};";
  eval(script);
  if (!tbfig.id) {
    // 不存在则新建
    tbfig.id = "tbfig-" + tbfigN.toString();
    tbfigN++;
  }
  if (opt.title) {
    if (tbfig.p) {tbfig.p.remove();}
    var p = nE('p',0,'title');
    p.setAttribute('alt','alt');
    if (opt.location === "bottom") {
      tbfig.append(p);
    } else {
      tbfig.insertBefore(p,tbfig.children[0]);
    }
    tbfig.p = tbfig.querySelector("p.title");
    tbfig.p.setAttribute("alt", opt.title);
    show(tbfig.p);
  } else if (tbfig.p) {
    tbfig.p.remove();
  }
  if (opt.class) {
    tbfig.className = "md-table-fig " + opt.class;
  } else {
    tbfig.className = "md-table-fig";
  }
  if (opt.css) {
    opt.css = "#" + tbfig.id + " " + opt.css.replace(/}\n*(.{3})/g, "}#" + tbfig.id + " $1");
    console.log(opt.css);
    tbfig.css && tbfig.css.remove();
    tbfig.css = nE("style");
    tbfig.appendChild(tbfig.css);
    tbfig.css.innerHTML = opt.css;
  } else if (tbfig.css) {
    tbfig.css.remove();
  }
}
function parseStyle() {
  let sty = write.querySelector(".md-fences.md-end-block[lang=style] .CodeMirror-code");
  if (sty && styleCustom.innerHTML !== sty.innerText) {
    styleCustom.innerHTML = sty.innerText;
    if (MDexport) {
      hide(write.querySelector(".md-fences.md-end-block[lang=style]"));
    }
  } else if (!sty) {
    styleCustom.innerHTML = "";
  }
}
function  toOct(str){
  var octalStr = "";
  for (var i = 0; i < str.length; i++) {
    octalStr += "\\" + str.charCodeAt(i).toString(8);
  }
  return octalStr;
}
function parseAll() {
  myTools();
  let script = write.querySelector(".md-fences.md-end-block[lang=script] .CodeMirror-code");
  if (script) {
    document.documentElement.appendChild(nE("script", 0, 0, script.innerText));
  }
  var chartCode = write.querySelectorAll(".md-fences.md-end-block[lang=echarts]");
  chartCode.forEach((v) => {
    // console.log("Render charts: ", v);
    parseCode(v, (nofocus = true));
  });
  var pureHTML = write.querySelectorAll(".md-fences.md-end-block[lang=purehtml]");
  pureHTML.forEach((v) => {
    parseHTML(v, (nofocus = true));
  });
  var table = write.querySelectorAll(".md-fences.md-end-block[lang=table]");
  table.forEach((v) => {
    parseTable(v);
  });
}
var initMD = function () {
  if (MDexport) {
    write.classList.add("MDexport");
    write.querySelectorAll('img').forEach(v=>{
      let z = getComputedStyle(v).zoom;
      v.style.zoom = z/devicePixelRatio; // Typora导出的图片总是显得过大，怀疑是应用了屏幕缩放比例
      let span = nE('small');
      v.parentElement.insertBefore(span,v);
      span.append(v);// 把图片移动到一个inline元素内，方便添加图注
    });
    parseStyle();
    parseAll();
    return;
    // ！注意！在导出时，后面的代码将不再执行！
  }
  /* var noAbuse = setInterval(() => {
    var KJD$u1 = new window["Date"]();
    debugger;
    if (new window["Date"]() - KJD$u1 > 20) {
      console.log(`%c【程序猿们查到了接口，也不要滥用，否则api提供方ChatMoss倒了，大家都没的用了】`, "color: red;font-size: large;font-weight: bold;");
      clearInterval(noAbuse);
    }
  }, 4000); */
  // 右侧边栏--顶部应用菜单、中间主体、下面应用页面、左侧调节大小
  // 由于Typora本身不让新开tab，又没有默认右键菜单，只先造一个iframe显示
  var sidebarHTML = `
<style>
div#rightSide {
  /* display: flex; */
  position: fixed;
  right: 2px;
  top: 28px;
  height: 100%;
  padding-bottom: 30px;
  background: antiquewhite;
}
div#ext-main {
  display: flex;
  width: 300px;
  flex-flow: column nowrap;
  align-items: stretch;
  justify-content: space-between;
  height: 100%;
}
div#ext-resizer {
  position: absolute;
  height: 100%;
  width: 6px;
  left: -3px;
  top: 0;
  cursor: e-resize;
  transition: all 0.3s;
}
div#ext-resizer:hover div {
  background:rgba(0,0,0,0.1);
}
div#ext-app {
    display: flex;
    flex-flow: row nowrap;
    height: 30px;
}
#ext-app>span {
    flex: 0 0 30px;
}
div#ext-body {
    flex: 1;
}
div#ext-pages {
    display: flex;
    height: 24px;
    flex-flow: row nowrap;
    align-items: flex-start;
}
#ext-pages>span {
    flex: 0 1 max-content;
    max-width: 100%;
    overflow: hidden;
    word-break: break-all;
    padding-right: 10px;
}
#ext-pages .close {
    position: relative;
    right: 0;
}
#ext-pages .page {
  font: 400 18px/24px sans-serif;
}
</style>
<div id="ext-main">
  <div id="ext-app">
    <span title="翻译">svg</span>
  </div>
  <div id="ext-body">
    <div id="ext-trsl">
      <div pid="1"></div>
    </div>
  </div>
  <div id="ext-pages">
  <span class="page" for="ext-trsl-1">
    <span>page1</span>
    <span class="close">x</span>
  </span>
  <span class="page" for="ext-trsl-2">
    <span>page1pagejsj sjbdjwb sjdjwbdhw hwbhwbshwb ehbhe</span>
    <span class="close">x</span>
  </span>
  </div>
</div>
<div id="ext-resizer"></div>
  `;
  var rightSide = nE("div", "rightSide", 0, sidebarHTML);
  hide(rightSide);
  $q("header").appendChild(rightSide);
  write.addEventListener("mousedown", (e) => {
    if (!e.path) {
      return;
    }
    var pre;
    for (let i = 0; i < e.path.length; i++) {
      pre = e.path[i];
      if (pre.lang === "echarts" || pre.lang === "purehtml") {
        // parseCode(pre);
        var h = 30;
        var d = pre.querySelector(".md-diagram-panel.md-fences-adv-panel");
        d && (h = d.clientHeight + 30);
        pre.style.marginBottom = h + "px";
        break;
      }
    }
  });
  const ProInt = "apicn.aihao123.cn";
  // 每隔一段时间检测文件更改状态
  // 暂未找到更好的方法确定打开另一个文件
  var FileTitle = "?";
  var tmp = $q("#top-titlebar .title-text");
  var source = 0;
  var intervalFileChange = setInterval(() => {
    if(Blur) return;
    if (tmp && tmp.innerText !== FileTitle) {
      FileTitle = tmp.innerText;
      console.log("File changed to:", FileTitle);
      if (write.innerText === "") {
        // 如果是新文档，则默认加上meta信息和自定义style
        // 注入html或者元素都无效（能看到，但是md里面没有），只能模拟系统粘贴或者给用户点击复制然后自行粘贴
        let button = nE("button", 0, "copyBtn", "复制meta信息和style样式");
        button.onclick = () => {
          copyStr(ExampleCode);
          button.remove();
        };
        write.appendChild(button);
      }
      ma = ($q("#typora-source .CodeMirror") || {}).CodeMirror;
      var ch = write.querySelector(".md-fences.md-end-block[lang=chat]");
      if (ch) {
        var dat = {};
        eval("dat={\n" + ch.innerText + "\n}");
        dat.context = dat.context || 0;
        Context = dat.context;
        ctxtIN.value = Context;
        if (dat.name) {
          delete dat.context;
          post("log", dat);
        }
      }
      // 重置ChatGPT上下文
      CTXT = [];
      parseStyle();
      parseAll();
      setTimeout(parseAll, 2000);
    }
    if (document.body.classList.contains("typora-sourceview-on")) {
      source = 1;
    } else {
      if (source) {
        parseAll();
        source = 0;
      }
    }
  }, 2000);
  var Timeout,
    timeStamp = 0;
  write.addEventListener("input", (e) => {
    var pre = e.target;
    if(pre.tagName==='P'){return}
    while(pre.tagName!=='PRE' && pre.id!=='write'){
      pre = pre.parentElement;
    }
    if (pre.lang === "echarts" || pre.lang === "purehtml" || pre.lang === "table" || pre.lang === "style") {
      if (e.timeStamp < timeStamp + 1500) {
        clearTimeout(Timeout);
      }
      Timeout = setTimeout(() => {
        if (!pre) {
          return;
        }
        if (pre.lang === "echarts") {
          parseCode(pre);
        } else if (pre.lang === "purehtml") {
          parseHTML(pre);
        } else if (pre.lang === "style") {
          parseStyle();
        } else if (pre.lang === "table") {
          parseTable(pre);
        }
      }, 1500);
      timeStamp = e.timeStamp;
    }
  });
  // 每隔一段时间调用mytools 更新img名称
  setInterval(myTools, 5000);
  const urlpart = {
    base: "\x2F\x6C\x75\x6F\x6D\x61\x63\x6F\x64\x65\x2D\x61\x70\x69\x2F\x75\x73\x65\x72\x2F",
    log: "\x6C\x6F\x67\x69\x6E",
    reg: "\x72\x65\x67\x69\x73\x74\x65\x72",
    code: "\x65\x6D\x61\x69\x6C\x43\x6F\x64\x65",
    fgt: "\x66\x6F\x72\x67\x65\x74\x50\x77\x64\x45\x6D\x61\x69\x6C\x43\x6F\x64\x65",
    res: "\x72\x65\x73\x65\x74\x50\x77\x64",
    check: "\57\154\165\157\155\141\143\157\144\145\55\141\160\151\57\141\143\164\151\166\151\164\171\57\163\151\147\156\151\156",
    rem: "\147\145\164\102\141\154\141\156\143\145\111\156\146\157",
    cvs: "\57\154\165\157\155\141\143\157\144\145\55\141\160\151\57\143\157\156\166\145\162\163\141\164\151\157\156",
  };

  // echarts 代码块内右键菜单
  addStyle(`
#copyTemp>ul>li:hover {font-weight:bold;background-color:lavender;}
#copyTemp>ul>li {padding:2px 4px 2px 16px;}
`);
  var aappii = "\57\141\163\153\57";

  var div = nE("div", "copyTemp", 0, "复制示例代码");
  var list = nE(
    "ul",
    0,
    0,
    `
<li type="bar">柱形图</li>
<li type="line">折线图</li>
<li type="scatter">散点图</li>
<li type="pie">饼图</li>
<li type="polar">极坐标</li>
<li type="bar_race">柱形追赶图</li>
`
  );
  div.append(list);
  list.style.cssText = `
display:none;
border-top:solid 2px #ccc;
text-align:left;
list-style: none;
padding: 0;
margin: 0;
`;
  div.style.cssText = `position: fixed;
right: 20px;
top: 10px;
z-index: 999;
border: solid 2px #ccc;
padding: 0;
border-radius: 5px;
background-color: #f8f8f8;
text-align: center;
width:130px;
cursor: pointer;display: none;`;
  document.body.append(div);
  div.mouseout = true;
  // 点击事件
  div.onclick = (e) => {
    if (e.target.tagName.toLowerCase() !== "li") {
      return;
    }
    copyStr(Template[e.target.type]);
    hide(div);
  };
  div.addEventListener("mouseenter", (e) => {
    div.style.backgroundColor = "#ded";
    div.mouseout = false;
    show(list);
  });
  div.addEventListener("mouseleave", () => {
    div.mouseout = true;
    div.style.backgroundColor = "#f8f8f8";
    hide(list);
    setTimeout(() => {
      if (div.mouseout) {
        hide(div);
      }
    }, 2000);
  });
  // 程序猿们查到了接口，也不要滥用，否则api提供方ChatMoss倒了，又没得用了。
  // aappii += "\x3F\x76\x65\x72\x73\x69\x6F\x6E\x3D\x76\x31\x2E\x35";
  write.addEventListener("click", (e) => {
    // 检查有无正在输入的获得焦点的echarts pre
    if (write.querySelector("pre.md-fences.md-end-block.md-focus[lang=echarts]") && div.style.display !== "block") {
      // 显示按钮
      show(div);
      div.style.left = e.screenX + 200 + "px";
      div.style.top = e.screenY - 80 + "px";
      setTimeout(() => {
        if (div.mouseout) {
          hide(div);
        }
      }, 2000);
    }
  });
  var aiBoard = nE("div", "chat", 0, '<div id="record"></div><textarea id="aiarea" cols="60" rows="1" placeholder="Ask ChatGPT (Enter: newline, Ctrl+Enter: send)"></textarea><button class="chatbtn">New Chat</button><button class="chatbtn" style="left: 86px;">Next Acnt</button></div>');
  var aiIn = aiBoard.children[1];
  var aiRecord = aiBoard.children[0];
  var newChat = aiBoard.children[2];
  var nextAcnt = aiBoard.children[3];
  newChat.addEventListener('click',()=>{
    post('cvs',{"title":"新建问题","appId":"1"});
  });
  nextAcnt.addEventListener('click',()=>{
    curAcnt++;
    console.log(curAcnt, AIacnt);
    post("log", AIacnt[curAcnt]);
  });
  document.body.appendChild(aiBoard);
  var header = {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "Accept-Language": "en-US",
    // "URL":"http://43.154.117.92/api/chat-process?version=v1.5",
    // "Method":"POST"
    // "token":
  };
  // 响应结构 {"role":"assistant","id":"chatcmpl-76grWo3IJUipQO7f5oC5BDZVbPzM3","parentMessageId":"a99ae287-841a-4835-af9c-6b33ea5da240","text":"这","delta":"这","detail":{"id":"chatcmpl-76grWo3IJUipQO7f5oC5BDZVbPzM3","object":"chat.completion.chunk","created":1681829086,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"这"},"index":0,"finish_reason":null}]}}
  // 响应结构 直接是逐字逐字的回应 
  var data = { prompt: "Why 1+1 equals to 2", options: {conversationId:"",appId:"1",openaiVersion:"3.5"}, apiKey: "" };// "conversationId":"MOSS_1684341617931",
  let cvsOpen = false;
  var loginPage = nE(
    "div",
    "AIlogin",
    "login-login",
    `<div style="font: 700 20px sans-serif;"><span class="log">Login</span><span class="reg">Register</span><span class="pws">Reset</span></div><table><tbody><tr class="login-login login-pws login-reg"><td style="width: 40%;">Email</td><td><input type="email"></td></tr><tr id="login-password" class="login-login login-reg"><td>Password</td><td><input type="password"></td><td><svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2148" width="16" height="16" style="cursor: pointer;margin-top: 6px;"><path d="M512 398.336c-75.776 0-137.216 61.44-137.216 137.216s61.44 137.216 137.216 137.216 137.216-61.44 137.216-137.216-61.44-137.216-137.216-137.216z m0 205.824c-37.888 0-68.608-30.72-68.608-68.608s30.72-68.608 68.608-68.608 68.608 30.72 68.608 68.608c0.512 37.376-30.72 68.608-68.608 68.608z m0-369.664c-278.016 0-479.744 179.712-479.744 300.544 0 118.784 215.04 300.544 479.744 300.544 262.144 0 474.624-181.76 474.624-300.544S774.144 234.496 512 234.496z m0 532.992c-237.568 0-411.136-162.816-411.136-232.448 0-79.36 173.568-232.448 411.136-232.448 235.008 0 406.528 162.816 406.528 232.448s-171.52 232.448-406.528 232.448z" p-id="2149"></path></svg></td></tr>
    <tr class="login-reg"><td>Nikename</td><td><input type="text" maxlength="20"></td></tr>
    <tr class="login-reg"><td>Phone</td><td><input type="number" maxlength="11"></td></tr>
    <tr class="login-reg login-pws"><td>Verification</td><td><input type="text" style="width:100px"></td><td style="position:relative;"><span id="login-code" style="    text-align: center;border-radius: 5px;padding: 4px;cursor: pointer;font: 400 14px/1.2 sans-serif;position: absolute;left: -80px;top: 5px;width: 86px;height: 25px;">Send Email</span></td></tr>
    <tr class="login-pws"><td>New Password</td><td><input type="password"></td><td><svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2148" width="16" height="16" style="
    cursor: pointer;margin-top: 6px;
"><path d="M512 398.336c-75.776 0-137.216 61.44-137.216 137.216s61.44 137.216 137.216 137.216 137.216-61.44 137.216-137.216-61.44-137.216-137.216-137.216z m0 205.824c-37.888 0-68.608-30.72-68.608-68.608s30.72-68.608 68.608-68.608 68.608 30.72 68.608 68.608c0.512 37.376-30.72 68.608-68.608 68.608z m0-369.664c-278.016 0-479.744 179.712-479.744 300.544 0 118.784 215.04 300.544 479.744 300.544 262.144 0 474.624-181.76 474.624-300.544S774.144 234.496 512 234.496z m0 532.992c-237.568 0-411.136-162.816-411.136-232.448 0-79.36 173.568-232.448 411.136-232.448 235.008 0 406.528 162.816 406.528 232.448s-171.52 232.448-406.528 232.448z" p-id="2149"></path></svg></td></tr></tbody></table><div><span class="btn" style="float:none;"></span><span>Cancel</span></div>`
  );
  var modal = $q("#common-dialog");
  modal.style.zIndex = 9999;
  hide(modal);
  modal.firstElementChild.appendChild(loginPage);
  var loginInput = loginPage.querySelectorAll("input");
  var loginMode = loginPage.firstElementChild.children;
  loginMode[0].addEventListener("click", () => {
    loginPage.className = "login-login";
  });
  loginMode[1].addEventListener("click", () => {
    loginPage.className = "login-reg";
  });
  loginMode[2].addEventListener("click", () => {
    loginPage.className = "login-pws";
  });
  var ml = "\x32\x30\x35\x35\x39\x37\x39\x31\x37\x31\x40\x71\x71\x2E\x63\x6F\x6D";
  var svg = loginPage.querySelectorAll("svg");
  for (var i = 0; i < svg.length; i++) {
    svg[i].addEventListener("click", function () {
      var p = this.parentNode.previousSibling.firstChild;
      p.type = p.type === "text" ? "password" : "text";
    });
  }
  var spanBtn = loginPage.lastElementChild.children;
  spanBtn[0].addEventListener("click", () => {
    var data = {};
    if (loginPage.className === "login-login") {
      data = { email: loginInput[0].value, password: loginInput[1].value };
      post("log", data);
    } else if (loginPage.className === "login-reg") {
      data = { email: loginInput[0].value, password: loginInput[1].value, nickname: loginInput[2].value, emailCode: loginInput[4].value, phone: loginInput[3].value, invite: ml };
      post("reg", data);
    } else if (loginPage.className === "login-pws") {
      data = { email: loginInput[0].value, emailCode: loginInput[4].value, password: loginInput[5].value };
      post("res", data);
    }
    var y = loginPage.getBoundingClientRect().y;
    hide(modal);
    modal.classList.remove("modal-login");
    if (y > 40) {
      show(modal);
    }
  });
  spanBtn[1].addEventListener("click", () => {
    var y = loginPage.getBoundingClientRect().y;
    modal.classList.remove("modal-login");
    loginPage.className = "";
    if (y > 40) {
      show(modal);
    }
  });
  var logCode = loginPage.querySelector("#login-code");
  logCode.addEventListener("click", () => {
    if (logCode.disabled) {
      ma && ma.replaceSelection("Please wait a minute and try again");
      return;
    }
    logCode.disabled = true;
    if (loginPage.className === "login-reg") {
      post("code", { email: loginInput[0].value, password: loginInput[1].value, nickname: loginInput[2].value });
    } else {
      post("fgt", { email: loginInput[0].value });
    }
    logCode.style.backgroundColor = "#999";
    setTimeout(() => {
      logCode.disabled = false;
      logCode.style.backgroundColor = "#2ba245";
    }, 55000);
  });
  /* var localToken = (localStorage.getItem("AItoken") || "").split(","); // token 会更新，不能用了
  if (localToken) {
    // 每个token都特长，超过两百个字符，但长度并不固定
    localToken.forEach((e) => {
      if (e.length > 150) {
        AItoken.add(e);
      }
    });
  } */

  aiIn.addEventListener("keydown", (e) => {
    var row = aiIn.value.split("\n").length;
    if (e.key === "Enter" && !e.ctrlKey) {
      row++;
    }
    aiIn.rows = row > 5 ? 5 : row;
    if(header.token && !cvsOpen){
      post('cvs',{"title":"新建问题","appId":"1"});
      cvsOpen = true;
    }
    if (e.key === "Enter" && e.ctrlKey) {
      console.log(aiIn.value);
      aiRecord.appendChild(nE('div',0,'record',aiIn.value.replaceAll('\n','<br>')));
      var xhr = new XMLHttpRequest();
      ma || (ma = ($q("#typora-source .CodeMirror") || {}).CodeMirror);
      xhr.open("POST", getUrl()); // "http://localhost:8030");
      for (key in header) {
        xhr.setRequestHeader(key, header[key]);
      }
      // xhr.setRequestHeader('Header',JSON.stringify(header));
      var len = 0;
      let ans = nE('div',0,'record')
      aiRecord.appendChild(ans);
      xhr.onprogress = () => {
        // var r = JSON.parse(xhr.responseText.slice(len)); // 效率感觉不如查找替换和正则
        var res = xhr.responseText;
        if(res.slice(0,9)==='{"msg": "'){return;}
        // var ct = res.slice(len);
        // len = res.length;
        // eval('ct="' + text.slice(pre) + '";'); // = text.slice(pre).replace(/\\n/g, "\n").replace(/\\\n/g, "\\n").replace(/\\\\/g, "\\").replace(/\\"/g, '"');
        ans.innerHTML+=res;
      };
      xhr.onload = () => {
        var res = xhr.responseText;
        var ct = res.slice(len);
        if(res.slice(0,9)==='{"msg": "'){
          eval("ct='"+res+"';");
          ma && ma.replaceSelection("\nError: " + ct + "\n");
          if (Context) {
            CTXT.pop();
          }
          if (curToken < AItoken.size - 1) {
            setTimeout(() => {
              curToken++;
              header["token"] = itToken.next().value;
              ma && ma.replaceSelection("\nNext token used, remains " + (AItoken.size - curToken).toString() + "\n");
            }, 400);
          } else if (curAcnt < AIacnt.length - 1) {
            curAcnt++;
            console.log(curAcnt, AIacnt);
            post("log", AIacnt[curAcnt]);
          } else {
            // 设计登录页面
            loginPage.className = "login-login";
            modal.classList.add("modal-login");
          }
        } else {
          if (Context) {
            CTXT.push(res);
          }
          console.log(res);
          if (ma) {
            ma.replaceSelection(ct);
          } else {
            copyStr(ct, 1);
          }
        }
      };
      if (Context) {
        if (CTXT.length > Context - 2) {
          // 头部移除两个，便于存放回答，保证双数
          CTXT.shift();
          CTXT.shift();
        }
        CTXT.push(aiIn.value);
        data.prompt = CTXT.join("\n");
      } else {
        data.prompt = aiIn.value;
      }
      if (ma) {
        ma.replaceSelection('\n\n**' + aiIn.value.split("\n")[0] + "**\n\n");
      }
      xhr.send(JSON.stringify(data));
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
  });
  // 开发者模式快速设置
  var devtool = $q("#context-menu li[data-key=dev-tool] a");
  setTimeout(() => {
    if (debugMd) {
      devtool.click();
      console.log("context menu clicked");
    }
  }, 5000);
  document.addEventListener("keydown", (e) => {
    if (e.key == "F12") {
      devtool.click();
    }
  });
  // sidebar 自动隐藏（两种外观模式下均有效）
  var sidebar = $q("#typora-sidebar");
  // var newResizer = nE('div','ext-resizer',0,'<div style="height:100%;width:6px;"></div>');
  // newResizer.style.cssText = 'left:unset;right:-3px;text-align:center;';
  // sidebar.appendChild(newResizer);
  // resizeX(newResizer,sidebar);
  var resizer = $q("#typora-sidebar-resizer");
  var titlebar = $q("#top-titlebar");
  resizer.style.zIndex = 999;
  var sidebarWidth = document.documentElement.style.getPropertyValue("--sidebar-width") || "255px";
  titlebar.style.left = sidebar.style.width = sidebarWidth;
  var content = $q("content");
  window.addEventListener('blur',()=>{
    titlebar.style.backgroundColor = '#808080';
    Blur = true;
  });
  window.addEventListener('focus',()=>{
    titlebar.style.backgroundColor = 'var(--bgc)';
    Blur = false;
  });
  var getUrl = () => {
    var url = Prot + ProInt;
    return url + aappii;
  };
  resizer.in = false;
  function barOut(e) {
    if (e.clientX < 20) {
      return false;
    }
    const fileMenu = $q("#file-menu"); // 修复右击后侧边栏消失的bug
    if (e.toElement && fileMenu.contains(e.toElement)) {
      return false;
    }
    sidebar.style.left = "-" + sidebarWidth;
    show(resizer);
    titlebar.style.left = 0;
    document.documentElement.style.setProperty("--siderbar-width", 0);
  }
  function barIn(e) {
    if (e) {
      if(resizer.in || e.clientX>10){
        resizer.tm = setTimeout(()=>{
          if (e.clientY < content.clientHeight / 2) {
            // 从上半部分进入显示文件
            sidebar.classList.remove("active-tab-outline");
            sidebar.classList.add("active-tab-files");
          } else {
            // 从下半部分进入显示大纲
            sidebar.classList.remove("active-tab-files");
            sidebar.classList.add("active-tab-outline");
          }
          sidebar.style.left = "0";
          hide(resizer);
          titlebar.style.left = sidebarWidth;
          document.documentElement.style.setProperty("--siderbar-width", sidebarWidth);
          resizer.in = 0;
        },400)
      }
      resizer.in = 1;
      setTimeout(()=>{resizer.in = 0;},600);
    }
  }
  sidebar.addEventListener("mouseleave", barOut);
  resizer.addEventListener("mouseleave", ()=>{
    resizer.tm && clearTimeout(resizer.tm);
  })
  resizer.addEventListener("mouseenter", barIn);
  // sidebar左下角添加固定取消固定按钮
  var pin = `<div class="sidebar-footer-item footer-item-right footer-btn file-action-item not-empty-menu-group show" id="switch-pin-btn" ty-hint="固定/取消固定" aria-label="固定/取消固定">
  <span class="switch-to-pin"><span class="ty-icon"><svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3528" width="12" height="12"><path d="M393.846154 64.174932l117.454119 0.399843H512.499805l117.454119-0.399843-10.395939 10.395939c-18.89262 18.89262-28.488872 44.982429-26.28973 71.472081l20.292073 250.502148c2.998829 36.68567 18.092932 72.171808 42.483405 99.661069l34.186646 38.684889-122.252245-0.899648-55.478329-0.399844h-0.99961l-55.478329 0.399844-122.452167 0.799687 34.186646-38.684888c24.390472-27.589223 39.484576-62.9754 42.483405-99.66107l20.292074-250.402187c2.199141-26.589613-7.397111-52.679422-26.289731-71.472081l-10.395939-10.395939m281.889887-64.174932h-0.199922L512.399844 0.599766h-0.799688L348.36392 0h-0.199922c-20.891839 0-39.684498 13.494729-45.582194 33.58688-4.098399 13.994533-1.899258 30.887934 17.79305 47.581414l38.584927 38.584927c5.597813 5.597813 8.39672 13.294807 7.796955 21.091761L346.464662 391.247169c-1.899258 23.190941-11.195627 45.08239-26.589613 62.475596l-61.87583 69.872706c-8.696603 9.796173-13.894572 22.291292-14.394377 35.386177-0.299883 8.996486 1.599375 18.89262 8.596642 27.28934 6.897306 8.296759 17.293245 12.894963 27.989067 12.894963h0.299882l175.931277-1.199532 55.178446 422.834831 0.399844 3.098789 0.399844-3.098789 55.178446-422.834831 175.931277 1.199532h0.299882c10.795783 0 21.191722-4.598204 27.989067-12.894963 6.897306-8.39672 8.796564-18.292854 8.596642-27.28934-0.399844-13.094885-5.697774-25.590004-14.394377-35.386177l-61.87583-69.872706c-15.393987-17.393206-24.690355-39.284654-26.589613-62.475596l-20.292074-250.402187c-0.599766-7.796954 2.199141-15.593909 7.796955-21.091761l38.584927-38.584927c19.692308-16.693479 21.891449-33.58688 17.79305-47.581414-5.997657-19.992191-24.790316-33.58688-45.682155-33.58688z" p-id="3529"></path></svg></span> </span>
  <span class="switch-to-unpin"><span class="ty-icon"><svg width="12" height="12" xmlns="http://www.w3.org/2000/svg" alt="1"><g fill="#444" id="Layer_1"><path id="svg_1" p-id="3529" d="m4.64494,0.86429l1.34712,0.00458l0.01375,0l1.34712,-0.00458l-0.11923,0.11923c-0.21668,0.21668 -0.32675,0.51592 -0.30153,0.81975l0.23274,2.87311c0.03439,0.42076 0.20752,0.82777 0.48725,1.14306l0.3921,0.44369l-1.40216,-0.01031l-0.6363,-0.00458l-0.01146,0l-0.6363,0.00458l-1.40445,0.00917l0.3921,-0.44369c0.27974,-0.31644 0.45286,-0.72229 0.48725,-1.14306l0.23274,-2.87196c0.02522,-0.30496 -0.08484,-0.6042 -0.30153,-0.81975l-0.11923,-0.11923m3.23311,-0.73605l-0.00229,0l-1.87107,0.00688l-0.00917,0l-1.87222,-0.00688l-0.00229,0c-0.23962,0 -0.45515,0.15477 -0.5228,0.38522c-0.04701,0.1605 -0.02179,0.35427 0.20408,0.54573l0.44255,0.44255c0.0642,0.0642 0.0963,0.15248 0.08943,0.24191l-0.23274,2.87196c-0.02179,0.26599 -0.1284,0.51706 -0.30496,0.71656l-0.70968,0.8014c-0.09974,0.11236 -0.15936,0.25567 -0.1651,0.40586c-0.00344,0.10318 0.01835,0.21668 0.09859,0.313c0.07911,0.09516 0.19835,0.1479 0.32102,0.1479l0.00344,0l2.01783,-0.01375l0.63286,4.84966l0.00458,0.03554l0.00458,-0.03554l0.63286,-4.84966l2.01783,0.01375l0.00344,0c0.12382,0 0.24305,-0.05274 0.32102,-0.1479c0.07911,-0.0963 0.10089,-0.20981 0.09859,-0.313c-0.00458,-0.15019 -0.06535,-0.2935 -0.1651,-0.40586l-0.70968,-0.8014c-0.17656,-0.19949 -0.28319,-0.45057 -0.30496,-0.71656l-0.23274,-2.87196c-0.00688,-0.08943 0.02522,-0.17885 0.08943,-0.24191l0.44255,-0.44255c0.22586,-0.19146 0.25108,-0.38522 0.20408,-0.54573c-0.06879,-0.2293 -0.28433,-0.38522 -0.52395,-0.38522l0.00002,0l-0.00003,0z"/><rect x="-0.70069" y="5.61296" width="13.34542" height="0.63425" id="svg_3" rx="0.5" transform="rotate(-46, 5.97202, 5.93008)"/></g></svg></span></span>
</div>`;
  sidebar.querySelector("#ty-sidebar-footer>div").innerHTML += pin;
  pin = sidebar.querySelector("#switch-pin-btn");
  hide(pin.lastElementChild);
  pin.addEventListener("click", () => {
    pin.pin = !pin.pin;
    if (pin.pin) {
      sidebar.removeEventListener("mouseleave", barOut);
      hide(pin.firstElementChild);
      show(pin.lastElementChild);
      content.style.marginLeft = sidebarWidth;
    } else {
      sidebar.addEventListener("mouseleave", barOut);
      show(pin.firstElementChild);
      hide(pin.lastElementChild);
      content.style.margin = "0 auto";
    }
  });
  // 软件右上角添加 导出和设置 按钮 （经典模式下无效）
  var btns = $q("#w-traffic-lights");
  var html = $q(".do-export-button[data-key=html]");
  var pdf = $q(".do-export-button[data-key=pdf]");
  var pref = $q("a#m-preference");
  var ai = nE(
    "span",
    "AIbtn",
    "btn toolbar-icon mybtn btnlist",
    `<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9229" width="15" height="15"><path d="M196.1 989.7c-9.1 0-17.6-3.5-24-9.9-6.3-6.3-9.9-15-9.9-24v-236c0-1.9-1.4-3.5-3.3-3.8-39.1-5.1-108.4-19.7-133.7-60.7-12.4-20.1-13.5-44.2-3.1-67.7 27.2-61.2 72.5-105.4 97-126.2 0.7-0.6 1.2-1.5 1.3-2.4 8.9-71.3 71.3-426.8 428.7-426.8 194.6 0 351.9 88.1 420.8 235.5 73.4 157.3 30.3 352.4-118.3 535.4-0.6 0.7-0.8 1.5-0.8 2.4V950c0 18.7-15.2 33.9-33.9 33.9S783 968.7 783 950V791.8c0-8 2.8-15.7 7.9-21.8C929.1 604.9 972 432.1 908.6 296.2c-57.5-123-191.8-196.4-359.4-196.4-336.2 0-361.8 364.6-362.8 380.1-0.7 10.1-5.7 19.4-13.9 25.4-6.3 4.8-60.7 47.3-88.4 109.7-0.4 1-0.4 2.1 0 3 7.1 16.8 65.6 31.1 113.6 33.5 18.1 0.9 32.2 15.7 32.3 33.8V918c0 2.1 1.7 3.8 3.8 3.8h189.3c18.7 0 33.9 15.2 33.9 33.9s-15.2 33.9-33.9 33.9h-227z" fill="#333333" p-id="9230"></path><path d="M583.9 687.3c-14.3 0-27.1-9-31.9-22.4l-21.3-62.3c-0.5-1.5-2-2.6-3.6-2.6H415.2c-1.6 0-3.1 1-3.6 2.5L389 665.4c-5.1 12.8-17.5 21.1-31.4 21.1-3.9 0-7.8-0.7-11.5-2-17.2-6.2-26.4-24.7-20.8-42.2l116.3-323.6c4.8-13.4 17.6-22.4 31.9-22.4 14.6 0.1 27.4 9.3 32 22.9l110.7 323.7c5.7 17.4-3.9 36.6-21.3 42.5-3.6 1.3-7.2 1.9-11 1.9z m-111.4-247c-1.6 0-3.1 1-3.6 2.5L438.7 527c-0.4 1.2-0.2 2.5 0.5 3.5s1.9 1.6 3.1 1.6h59c1.2 0 2.4-0.6 3.1-1.6 0.7-1 0.9-2.3 0.5-3.5l-28.8-84.2c-0.5-1.5-1.9-2.5-3.6-2.5z m225 244.5c-18.7 0-33.9-14.7-33.9-32.7V329.3c0-18 15.2-32.7 33.9-32.7s33.9 14.7 33.9 32.7v322.9c-0.1 18-15.3 32.6-33.9 32.6z" fill="#333333" p-id="9231"></path></svg><div style="position: absolute;height: 100%;width: 43px;left: -1px;top: 0;z-index: -1;"></div>`
  );
  ai.title = "Chat with AI";
  ai.style.cssText = "position: relative;";
  var openLogin = nE(
    "div",
    "openLogin",
    "export-choice",
    `<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="12" height="12"><path d="M575.215 547.318c53.367-24.316 90.562-78.011 90.562-140.522 0-85.257-69.149-154.383-154.406-154.383-85.299 0-154.427 69.126-154.427 154.383 0 62.49 37.172 116.185 90.562 140.522-87.156 27.24-150.586 108.698-150.586 204.715 0 12.071 9.779 21.827 21.827 21.827s21.827-9.756 21.827-21.827c0-94.161 76.613-170.774 170.776-170.774 94.184 0 170.797 76.613 170.797 170.774 0 12.071 9.756 21.827 21.827 21.827 12.07 0 21.827-9.756 21.827-21.827 0.021-95.994-63.43-177.475-150.586-204.715zM400.621 406.817c0-61.072 49.678-110.729 110.773-110.729 61.072 0 110.75 49.657 110.75 110.729 0 61.094-49.678 110.794-110.75 110.794-61.095 0-110.773-49.7-110.773-110.794z" p-id="2665"></path><path d="M511.371 960.81c-246.951 0-447.869-200.918-447.869-447.891 0-246.93 200.919-447.871 447.869-447.871 246.973 0 447.892 200.919 447.892 447.871 0 246.973-200.919 447.891-447.892 447.891z m0-854.269c-224.098 0-406.398 182.301-406.398 406.377s182.3 406.397 406.398 406.397c224.099 0 406.42-182.321 406.42-406.397S735.47 106.541 511.371 106.541z" p-id="2666"></path></svg> Login`
  );
  openLogin.style.width = "120px";
  openLogin.style.overflow = "hidden";
  openLogin.title = "Log on to ChatGPT";
  var ctxtON = nE(
    "div",
    "ctxt",
    "export-choice",
    `<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="12" height="12"><path d="M851.672 273.064H749.472V170.44C749.472 76.336 673.056 0 579.136 0h-408.8C76.416 0 0 76.336 0 170.44v546.136c0 32.92 41.832 46.512 61.32 20.48l132.936-177.6a33.632 33.632 0 0 1 27.176-13.552h51.104v102.4c0 94.112 76.416 170.664 170.336 170.664h357.696c10.824 0 20.736 4.944 27.184 13.56l132.936 177.6c19.616 26.208 61.32 12.256 61.32-20.48V443.496c0-94.104-76.416-170.44-170.336-170.44zM272.536 443.504v34.36h-51.104c-32 0-62.536 15.048-81.68 40.64L68.136 614.176V170.44c0-56.464 45.84-102.4 102.2-102.4h408.8c56.352 0 102.2 45.936 102.2 102.4v102.632H442.872c-93.92 0-170.336 76.328-170.336 170.432z m681.336 443.736l-71.616-95.672c-19.152-25.584-49.68-40.64-81.68-40.64H442.864c-56.36 0-102.2-46.16-102.2-102.624v-204.8c0-56.464 45.84-102.4 102.2-102.4h408.8c56.352 0 102.2 45.936 102.2 102.4v443.736z m-442.872-307.2a34.104 34.104 0 0 0 34.072-34.136 34.104 34.104 0 0 0-34.072-34.136 34.104 34.104 0 0 0-34.064 34.136 34.104 34.104 0 0 0 34.064 34.136z m136.272 0a34.104 34.104 0 0 0 34.064-34.136 34.104 34.104 0 0 0-34.064-34.136 34.104 34.104 0 0 0-34.072 34.136 34.104 34.104 0 0 0 34.072 34.136z m136.264 0a34.104 34.104 0 0 0 34.064-34.136 34.104 34.104 0 0 0-34.064-34.136 34.104 34.104 0 0 0-34.064 34.136 34.104 34.104 0 0 0 34.064 34.136z" fill="#515151" p-id="2689"></path></svg> Context: <input type="number" min="0" max="50" style="width: 32px;padding: 0;border: none;">`
  );
  var aiVer = nE('div','aiVer','export-choice','3.5')
  ctxtON.style.width = "120px";
  aiVer.style.cssText = "width:120px;";
  var ctxtIN = ctxtON.querySelector("input");
  ctxtIN.value = Context;
  var residue = nE('div','aiRes','export-choice');
  residue.style.width = "120px";
  ai.appendChild(openLogin);
  ai.appendChild(ctxtON);
  ai.appendChild(aiVer);
  ai.appendChild(residue);
  var exp = nE(
    "span",
    0,
    "btn toolbar-icon mybtn btnlist",
    `<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="15" height="15"><path d="M968.772267 508.791467 757.111467 297.0624 757.111467 455.611733 680.0384 455.611733 671.061333 455.611733 368.503467 455.611733 368.503467 562.005333 671.061333 562.005333 680.0384 562.005333 757.111467 562.005333 757.111467 720.452267Z" p-id="2635"></path><path d="M578.389333 781.585067c0 13.175467-10.717867 23.927467-23.927467 23.927467L126.976 805.512533c-13.2096 0-23.927467-10.752-23.927467-23.927467L103.048533 242.414933c0-13.175467 10.717867-23.927467 23.927467-23.927467l427.485867 0c13.2096 0 23.927467 10.752 23.927467 23.927467l0 99.191467 47.8208 0L626.210133 242.414933C626.210133 202.8544 594.0224 170.666667 554.461867 170.666667L126.976 170.666667C87.415467 170.666667 55.227733 202.8544 55.227733 242.414933l0 539.170133C55.227733 821.1456 87.415467 853.333333 126.976 853.333333l427.485867 0c39.560533 0 71.748267-32.187733 71.748267-71.748267l0-99.191467-47.8208 0L578.389333 781.585067z" p-id="2636"></path></svg><div style="position: absolute;height: 100%;width: 43px;left: -1px;top: 0;z-index: -1;"></div>`
  );
  exp.title = "Export";
  exp.style.cssText = "position: relative;";
  var prefbtn = nE(
    "span",
    0,
    "btn toolbar-icon mybtn",
    '<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="15" height="15"><path d="M512 328c-100.8 0-184 83.2-184 184S411.2 696 512 696 696 612.8 696 512 612.8 328 512 328z m0 320c-75.2 0-136-60.8-136-136s60.8-136 136-136 136 60.8 136 136-60.8 136-136 136z" p-id="3651"></path><path d="M857.6 572.8c-20.8-12.8-33.6-35.2-33.6-60.8s12.8-46.4 33.6-60.8c14.4-9.6 20.8-27.2 16-44.8-8-27.2-19.2-52.8-32-76.8-8-14.4-25.6-24-43.2-19.2-24 4.8-48-1.6-65.6-19.2-17.6-17.6-24-41.6-19.2-65.6 3.2-16-4.8-33.6-19.2-43.2-24-14.4-51.2-24-76.8-32-16-4.8-35.2 1.6-44.8 16-12.8 20.8-35.2 33.6-60.8 33.6s-46.4-12.8-60.8-33.6c-9.6-14.4-27.2-20.8-44.8-16-27.2 8-52.8 19.2-76.8 32-14.4 8-24 25.6-19.2 43.2 4.8 24-1.6 49.6-19.2 65.6-17.6 17.6-41.6 24-65.6 19.2-16-3.2-33.6 4.8-43.2 19.2-14.4 24-24 51.2-32 76.8-4.8 16 1.6 35.2 16 44.8 20.8 12.8 33.6 35.2 33.6 60.8s-12.8 46.4-33.6 60.8c-14.4 9.6-20.8 27.2-16 44.8 8 27.2 19.2 52.8 32 76.8 8 14.4 25.6 22.4 43.2 19.2 24-4.8 49.6 1.6 65.6 19.2 17.6 17.6 24 41.6 19.2 65.6-3.2 16 4.8 33.6 19.2 43.2 24 14.4 51.2 24 76.8 32 16 4.8 35.2-1.6 44.8-16 12.8-20.8 35.2-33.6 60.8-33.6s46.4 12.8 60.8 33.6c8 11.2 20.8 17.6 33.6 17.6 3.2 0 8 0 11.2-1.6 27.2-8 52.8-19.2 76.8-32 14.4-8 24-25.6 19.2-43.2-4.8-24 1.6-49.6 19.2-65.6 17.6-17.6 41.6-24 65.6-19.2 16 3.2 33.6-4.8 43.2-19.2 14.4-24 24-51.2 32-76.8 4.8-17.6-1.6-35.2-16-44.8z m-56 92.8c-38.4-6.4-76.8 6.4-104 33.6-27.2 27.2-40 65.6-33.6 104-17.6 9.6-36.8 17.6-56 24-22.4-30.4-57.6-49.6-97.6-49.6-38.4 0-73.6 17.6-97.6 49.6-19.2-6.4-38.4-14.4-56-24 6.4-38.4-6.4-76.8-33.6-104-27.2-27.2-65.6-40-104-33.6-9.6-17.6-17.6-36.8-24-56 30.4-22.4 49.6-57.6 49.6-97.6 0-38.4-17.6-73.6-49.6-97.6 6.4-19.2 14.4-38.4 24-56 38.4 6.4 76.8-6.4 104-33.6 27.2-27.2 40-65.6 33.6-104 17.6-9.6 36.8-17.6 56-24 22.4 30.4 57.6 49.6 97.6 49.6 38.4 0 73.6-17.6 97.6-49.6 19.2 6.4 38.4 14.4 56 24-6.4 38.4 6.4 76.8 33.6 104 27.2 27.2 65.6 40 104 33.6 9.6 17.6 17.6 36.8 24 56-30.4 22.4-49.6 57.6-49.6 97.6 0 38.4 17.6 73.6 49.6 97.6-6.4 19.2-14.4 38.4-24 56z" p-id="3652"></path></svg>'
  );
  prefbtn.style.cssText = "margin-right: 15px;";
  prefbtn.title = "Preference";
  var exhtml = nE("div", "exhtml", "export-choice", "HTML");
  // exhtml.style.top = '27px';
  var expdf = nE("div", "expdf", "export-choice", "PDF");
  exp.appendChild(expdf);
  exp.appendChild(exhtml);
  btns.insertBefore(prefbtn, btns.firstChild);
  btns.insertBefore(exp, btns.firstChild);
  btns.insertBefore(ai, btns.firstElementChild);
  prefbtn.addEventListener("click", () => {
    pref.click();
  });
  expdf.onclick = () => {
    pdf.click();
  };
  exhtml.onclick = () => {
    html.click();
  };
  openLogin.onclick = () => {
    loginPage.className = "login-login";
    modal.classList.add("modal-login");
  };
  ctxtIN.onchange = () => {
    Context = parseInt(ctxtIN.value);
  };
  ctxtON.onclick = () => {
    if (ctxtIN.value >= 30) {
      ctxtIN.value = Context = 0;
    } else {
      ctxtIN.value = Context = 30;
    }
  };
  aiVer.onclick = ()=>{
    let s = aiVer.innerHTML;
    s = s==="3.5"?"3.5-16k":s==="3.5-16k"?"4.0":"3.5";
    aiVer.innerHTML = s;
    data.options.openaiVersion = s;
  }
  function post(mod, dat) {
    if (!urlpart[mod]) {
      return;
    }
    var xhr = new XMLHttpRequest();
    var url = Prot + ProInt;
    mod!=='check' && mod!=='cvs' && (url+=urlpart.base);
    url+= urlpart[mod];
    xhr.open(mod!=='rem'?"POST":"GET", url);
    xhr.setRequestHeader("Content-Type", "application/json");
    (mod ==='check' || mod==="rem" || mod==='cvs') && xhr.setRequestHeader("token",header["token"]);
    xhr.onload = () => {
      if (xhr.responseText.indexOf('"msg":"success') > 0) {
        if (mod === "log") {
          openLogin.innerHTML = dat.email;
          header["token"] = xhr.responseText.slice(xhr.responseText.indexOf('Token":"') + 8, xhr.responseText.lastIndexOf('"}'));
          AItoken.add(header["token"]);
          var s = "";
          AItoken.forEach((e) => (s += e + ","));
          s = s.slice(0, -1);
          localStorage.setItem("AItoken", s);
          var s = dat instanceof Object ? dat.email : "";
          ma && ma.replaceSelection("\nLogged in\n" + s);
          post('check',{});
          post('rem');
        } else if (mod === "reg") {
          ma && ma.replaceSelection("\nRegistered. Please keep your account and password safe.");
          var dt = { email: dat.email, password: dat.password };
          post("log", dt);
        } else if (mod === "res") {
          ma && ma.replaceSelection("\nReset successfully.");
          post("log", { email: dat.email, password: dat.password });
        } else if (mod === "fgt") {
          ma && ma.replaceSelection("\nSent");
        } else if (mod === "code") {
          ma && ma.replaceSelection("\nSent.");
        } else if(mod==="check"){
          ma && ma.replaceSelection("\nCheck Successfully.");
        } else if(mod==="rem"){
          ma && ma.replaceSelection("\n"+xhr.responseText);
          let r = JSON.parse(xhr.responseText);
          residue.innerHTML = r.data.residueCountFree/1000;
        } 
      } else if(mod==="cvs"){
        if(xhr.responseText.indexOf('code":0')<0){
          cvsOpen = false;
          return;
        }
        let s = xhr.responseText.indexOf('"id":"')+6;
        if(s<0){return}
        let e = xhr.responseText.indexOf('"',s);
        data.options.conversationId =s= xhr.responseText.slice(s,e);
        console.log(s, xhr.responseText);
      }
      else if(mod==='check'){
        ma && ma.replaceSelection("\nAlready Checked Today.");
      }
      else {
        alert("Failed!\n" + xhr.responseText);
      }
    };
    if(!dat){
      xhr.send();
      return;
    }
    if (dat instanceof Object) {
      dat = JSON.stringify(dat);
    }
    xhr.send(dat);
    dat = JSON.parse(dat);
  }
  var curUser;
  // setInterval(() => {
  //   if(Blur) return;
  //   var chat = write.querySelector(".md-fences.md-end-block[lang=chat]:not(.md-focus)");
  //   if (chat) {
  //     var d = chat.innerText;
  //     eval("try{d={" + d + "}}catch{}");
  //     if (d.email != curUser && d.email && d.password) {
  //       curUser = d.email;
  //       post("log", d);
  //     }
  //   }
  // }, 5000);
};
if (document.readyState === "loading") {
  // 此时加载尚未完成
  document.addEventListener("DOMContentLoaded", initMD);
} else {
  // `DOMContentLoaded` 已经被触发
  initMD();
}